package band.wukong.practice.webservice.kh.sample10;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author wukong(wukonggg@139.com)
 */
@WebService(
    endpointInterface = "band.wukong.practice.webservice.kh.sample10.BinaryService",
    targetNamespace = BinaryConst.SERVICE_NS,
    serviceName = BinaryConst.SERVICE_NAME,
    portName = BinaryConst.PORT_NAME
)
@BindingType(SOAPBinding.SOAP11HTTP_MTOM_BINDING)
public class BinaryServiceImpl implements BinaryService {

    private static final Logger logger = LoggerFactory.getLogger(BinaryServiceImpl.class);

    @Override
    public void upload(DataHandler handler) {
        logger.debug("handler.getContentType() = " + handler.getContentType());
        logger.debug("handler.getDataSource().getName() = " + handler.getDataSource().getName());

        FileOutputStream fos = null;
        InputStream is = null;
        try {
            fos = new FileOutputStream("D:/2.png");

            is = handler.getDataSource().getInputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }

            fos.flush();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();

        } finally {
            try {
                is.close();
                fos.close();

            } catch (IOException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
